$(function () {
    document.body.setAttribute("class", "bg-" + sessionStorage.getItem("bg"));
    function bgchange(bg) {
        let uid=parseInt(sessionStorage.getItem("uid"));
        $.ajax({
            type: "GET",
            url: "/bgchange/" + uid + "&" + bg,
            async: false,
            success: function (result) {
                sessionStorage.setItem("bg",bg);
            },
            error: function (errorMsg) {
                alert("修改失败");
            }
        });
    }

    let TalkSub = document.getElementById("messageInput");
    let clearMessage = document.getElementById("clearMessage");
    let TalkWords = document.getElementById("talkwords");

    document.getElementById("history").onclick = function () {
        openWin('/chatHistory1ByText/' + uid + '&' + oid + '&1/?text=', 620, 580);
    };

    TalkSub.onclick = function () {
        if (TalkWords.value === "") {
            // 消息为空时弹窗
            alert("消息不能为空");
        } else {
            sendMessage(TalkWords.value);
            setMyMessage(picSrc);
            TalkWords.value = "";
        }
    };

    clearMessage.onclick = function () {
        $("#words").empty();
        $("#talkwords").focus();
    };

    initEmoji();
    $("#sendImageBtn").click(function () {
        $("#sendImage").trigger("click");
    })
});

/**
 * 正则表达式显示消息中的emoji图片
 * @param message
 * @returns {*} 返回添加emoji图片标签后的消息
 */
function showEmoji(message) {
    var result = message,
        regrex = /\[EMOJI:\d+\]/g,
        match;
    while (match = regrex.exec(message)) {
        var emojiIndex = match[0].slice(7, -1);
        var emojiUrl = $("#emojiBaseUri").val().trim() + emojiIndex + ".gif";
        result = result.replace(match[0], '<img src="' + emojiUrl + '"/>');
    }
    return result;
}

/**
 * 显示用户发送的图片
 * @param user 用户名称
 * @param date 用户发送的时间（未格式化）
 * @param url 图片url
 */
function showNewImage(user, date, url) {
    var container = document.getElementById("historyMsg");
    var msgToDisplay = document.createElement('p');
    var dateTime = formatDate(date);
    msgToDisplay.innerHTML = '<span class="timespan">' + dateTime + '</span><br/>[' + user + '] : <br/>' +
        '<img class="img-thumbnail" src="' + url + '"/>';
    container.append(msgToDisplay);
    container.scrollTop = container.scrollHeight;
}

/**
 * 预加载emoji图片
 */
function initEmoji() {
    var emojiContainer = $("#emojiWrapper");
    var documentFragment = document.createDocumentFragment();
    for (var i = 69; i > 0; i--) {
        var emojiItem = document.createElement("img");
        emojiItem.src = $("#emojiBaseUri").val().trim() + i + ".gif";
        emojiItem.title = i;
        documentFragment.appendChild(emojiItem);

    }
    emojiContainer.append(documentFragment);

    $("#emoji").click(function (event) {
        emojiContainer.css("display", "block");
        event.stopPropagation(); //阻止事件的传递，防止body监听到
    });

    $("body").click(function (event) {
        if (event.target != emojiContainer) {
            emojiContainer.css("display", "none");
        }
    });

    $("#emojiWrapper").click(function (event) {
        console.log("dianji");
        var target = event.target;
        if (target.nodeName.toLowerCase() == "img") {
            console.log("dianji2");
            var talkwords = $("#talkwords");

            talkwords.val(talkwords.val() + "[EMOJI:" + target.title + "]");
            talkwords.focus();
        }
    })
}

function openWin(name, iWidth, iHeight) {
    //获得窗口的垂直位置
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
    //获得窗口的水平位置
    var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
    window.open(name, "history", 'height=' + iHeight + ',innerHeight=' + iHeight +
        ', width = ' + iWidth + ', innerWidth = ' + iWidth + ', top = ' + iTop + ', left = ' + iLeft +
        ', status = no, toolbar = no, menubar = no, location = no, resizable = no, scrollbars = 0, titlebar = no');
}

function formatDate(date, format) {
    if (!date) return;
    if (!format) format = "yyyy-MM-dd HH:mm:ss";
    switch (typeof date) {
        case "string":
            date = new Date(date.replace(/-/, "/"));
            break;
        case "number":
            date = new Date(date);
            break;
    }
    if (!date instanceof Date) return;
    var dict = {
        "yyyy": date.getFullYear(),
        "M": date.getMonth() + 1,
        "d": date.getDate(),
        "H": date.getHours(),
        "m": date.getMinutes(),
        "s": date.getSeconds(),
        "MM": ("" + (date.getMonth() + 101)).substr(1),
        "dd": ("" + (date.getDate() + 100)).substr(1),
        "HH": ("" + (date.getHours() + 100)).substr(1),
        "mm": ("" + (date.getMinutes() + 100)).substr(1),
        "ss": ("" + (date.getSeconds() + 100)).substr(1)
    };
    return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function () {
        return dict[arguments[0]];
    });
}

function setMyMessage(picSrc) {
    let time = new Date();
    let mytime = time.toLocaleTimeString(); //获取当前时间
    time.toLocaleString(); //获取日期与时间
    let str =
        '<li class="odd">' +
        '                <a class="user" href="#">' +
        '<img class="img-responsive avatar_ avatar_1" id="image" style="height: 50px;width: 50px" src="' + picSrc + '" alt="">' +
        // '<div id = "image" class="img-responsive avatar_"></div>' +
        '<span class="user-name">' +
        username +
        '</span></a>' +
        '                <div class="reply-content-box">' +
        '                    <span class="reply-time">' +
        mytime +
        '</span>' +
        '                    <div class="reply-content pr">' +
        '                        <span class="arrow">&nbsp;</span>' +
        showEmoji(TalkWords.value) +
        '                    </div>' +
        '                </div>' +
        '            </li>';
    //$("[id=image]").src = picSrc;

    Words.innerHTML = Words.innerHTML + str;
    // $("[id=image]").html(img);
}

function setMessage(item, time, oPicSrc) {
    let str =
        '<li class="even">\n' +
        '                <a class="user" href="#">' +
        // '<div id = "oImage" class="img-responsive avatar_"></div>' +
        '<img class="img-responsive avatar_" style="height: 50px;width: 50px" src="' + oPicSrc + '" alt="">' +
        '<span class="user-name">' +
        item.fromName +
        '</span></a>\n' +
        '                <div class="reply-content-box">\n' +
        '                    <span class="reply-time">' +
        time +
        '</span>\n' +
        '                    <div class="reply-content pr">\n' +
        '                        <span class="arrow">&nbsp;</span>\n' +
        showEmoji(item.messageText) +
        '                    </div>\n' +
        '                </div>\n' +
        '            </li>';
    //$("[id=oImage]").src = oPicSrc;

    Words.innerHTML = Words.innerHTML + str;
    //目标用户头像
    // let oPic = sessionStorage.getItem("oPic");
    // let oImg = document.createElement("img");
    // oImg.src = "data:image/jpeg;base64," + oPic;
    // oImg.width = 50;
    // oImg.height = 50;
    // $("[id=oImage]").html(oImg);
}